<script setup>
import Card from '@v/home-view/card.vue'
import { computed, onMounted, reactive, ref } from 'vue'
import CityInfo from '@v/home-view/city-info.vue'
import QuestionInfo from '@v/home-view/question-info.vue'
import IndexInfo from '@/views/home-view/index-info.vue'
import {
  queryArea,
  querySatisfactionArea,
  querySpecialIds,
} from '@/api/question'
import { Message } from 'element-ui'
import { queryBaseIndexList } from '@/api/city-index'

const areaInfo = ref([])
const areaInfo2 = ref([])
const cityOptions = ref([])
const specialCityOptions = ref([])
const cascaderProps = ref({
  value: 'pkid',
  label: 'areaName',
  checkStrictly: true,
  children: 'children',
})

const user = JSON.parse(localStorage.getItem('user')).user

let baseLevel = '0'

const handleRadioChange = () => {
  infoRef.value.inputData(params.value)
}

const handleRadioChange2 = () => {
  questionInfoRef.value?.inputData(params2.value)
}

const handleChangeArea = (val) => {
  
  const currentLevel = val.length
    ? val.length + Number(baseLevel) - 1
    : Number(baseLevel)
  params.value.level = currentLevel.toString()
  switch (currentLevel) {
    // case 0:
    //   params.value.regionId = ''
    //   params.value.streetId = ''
    //   params.value.communityId = ''
    //   break
    case 0:
      params.value.regionId = val[val.length - 1]
      params.value.streetId = ''
      params.value.communityId = ''
      break
    case 1:
      params.value.regionId = ''
      params.value.streetId = val[val.length - 1]
      params.value.communityId = ''
      break
    case 2:
      params.value.regionId = ''
      params.value.streetId = ''
      params.value.communityId = val[val.length - 1]
      break
  }
  infoRef.value.inputData(params.value)
}

const handleChangeArea2 = (val) => {
  const currentLevel = val.length
    ? val.length + Number(baseLevel) - 1
    : Number(baseLevel)
  params2.value.level = currentLevel.toString()
  switch (currentLevel) {
    case 0:
      params2.value.regionId = ''
      params2.value.streetId = ''
      params2.value.communityId = ''
      params2.value.regionName = ''
      break
    case 1:
      params2.value.regionId = val[val.length - 1]
      params2.value.streetId = ''
      params2.value.communityId = ''
      break
    case 2:
      params2.value.regionId = ''
      params2.value.streetId = val[val.length - 1]
      params2.value.communityId = ''
      params2.value.regionName = ''
      break
    case 3:
      params2.value.regionId = ''
      params2.value.streetId = ''
      params2.value.communityId = val[val.length - 1]
      params2.value.regionName = ''
      break
  }
  if (params2.value.regionId) {
    const node = findNodeById(cityOptions.value, params2.value.regionId)
    // console.log(node)
    if (node) {
      params2.value.regionName = node.areaName
    }
  }
  if (val.length === 0 && user.roleLevel === 2) {
    params2.value.regionName = user.areaName
  }
  questionInfoRef.value?.inputData(params2.value)
}

const indexOptions = ref([])
const indexChecked = ref('')

const questionInfoRef = ref()
const infoRef = ref()
const indexInfoRef = ref()

const findNodeById = (tree, targetId) => {
  // 遍历树中的每个节点
  for (let i = 0; i < tree.length; i++) {
    // 检查当前节点的ID是否为目标ID
    if (tree[i].areaCode === targetId || tree[i].pkid === targetId) {
      // 如果是的话，返回当前节点
      return tree[i]
    }

    // 如果当前节点有子节点，则递归在子节点中查找
    if (tree[i].children && tree[i].children.length > 0) {
      const foundNode = findNodeById(tree[i].children, targetId)
      // 如果在子节点中找到了，则返回找到的节点
      if (foundNode !== undefined) {
        return foundNode
      }
    }
  }

  // 如果在树中没有找到目标ID，则返回undefined
  return undefined
}

const removeChildrenAtLevel = (tree, targetLevel) => {
  // 遍历树中的每个节点
  for (let i = 0; i < tree.length; i++) {
    // 检查当前节点的level是否为目标level
    if (tree[i].level === targetLevel) {
      // 如果是的话，移除children属性
      delete tree[i].children
    }

    // 如果当前节点还有子节点，并且子节点的level也为目标level，则递归处理子节点
    if (tree[i].children && tree[i].children.length > 0) {
      removeChildrenAtLevel(tree[i].children, targetLevel)
    }
  }

  return tree
}

const getCurrentLevelCityOption = (data) => {
  // 获取当前级别
  const areaCode = user.refId
  return findNodeById(data, areaCode)
}

const params = ref({
  regionId: '',
  streetId: '',
  communityId: '',
  type: 'community',
  level: '',
})

const params2 = ref({
  regionId: '',
  streetId: '',
  communityId: '',
  level: '',
  type: 'region',
  regionName: '',
})

const getCurrentLevel = () => {
  const roleLevel = user.roleLevel
  const id = user.refId
  let obj = {
    regionId: '',
    streetId: '',
    communityId: '',
    type: 'community',
    level: '',
  }
  let obj2 = {
    regionId: '',
    streetId: '',
    communityId: '',
    level: '',
    type: 'region',
    regionName: '',
  }
  if (user.roleLevel === 3) {
    obj.type = 'community'
  }
  switch (roleLevel) {
    case 0:
    case 4:
    case 5:
      obj.level = '0'
      break
    case 2:
      obj.regionId = id
      obj.level = '1'
      obj2.regionId = id
      obj2.regionName = user.areaName
      break
    case 1:
      obj.streetId = id
      obj.level = '2'
      obj2.streetId = id
      break
    case 3:
      obj.communityId = id
      obj.level = '3'
      obj2.communityId = id
      break
  }
  obj2.level = obj.level
  baseLevel = obj.level
  params.value = obj
  params2.value = obj2
}

getCurrentLevel()

const getCityOptionList = () => {
  queryArea({})
    .then((res) => {
      if (res.success) {
        if (!res.data) return
        const tree = removeChildrenAtLevel(res.data, 2)
        const node = getCurrentLevelCityOption(tree)
        if (node) {
          // cityOptions.value = [node]
          cityOptions.value = node.children
        } else {
          cityOptions.value = []
        }
      } else {
        Message.error(res.message)
      }
    })
    .catch((err) => {
      console.log(err)
    })
}

const getSpecialIds = () => {
  querySpecialIds().then((res) => {
    if (res.success) {
      // console.log(res.data)
      if (res.data) {
        const { communityIds, streetIds, regionIds } = res.data
        specialRegionId.value = regionIds.concat(streetIds, communityIds)
      }
    }
  })
}

const specialCityOptionList = () => {
  querySatisfactionArea({})
    .then((res) => {
      if (res.success) {
        const tree = removeChildrenAtLevel(res.data, 2)
        const node = getCurrentLevelCityOption(tree)
        if (node) {
          specialCityOptions.value = [node]
        } else {
          specialCityOptions.value = []
        }
      } else {
        Message.error(res.message)
      }
    })
    .catch((err) => {
      console.log(err)
    })
}

const getSelectOption = () => {
  if (user.roleLevel === 1 || user.roleLevel === 3) {
    return
  }
  queryBaseIndexList({
    pageSize: 999,
    pageIndex: 1,
    status: 1,
  }).then((res) => {
    if (res.success) {
      indexOptions.value = res.data?.list || []
      if (indexOptions.value.length) {
        indexChecked.value = indexOptions.value[0].pkid
        indexInfoRef.value?.inputData(indexChecked.value)
      }
    } else {
      Message.error(res.message)
    }
  })
}

onMounted(() => {
  getCityOptionList()
  // getSpecialIds()
  // specialCityOptionList()
  // getSelectOption()
  infoRef.value.inputData(params.value)
  questionInfoRef.value?.inputData(params2.value)
  indexInfoRef.value?.inputData(indexChecked.value)
})

const handleChangeSelect = () => {
  // console.log(indexChecked.value)
  indexInfoRef.value?.inputData(indexChecked.value)
}

const specialRegionId = ref([
  '500103000000',
  '500104000000',
  '500105000000',
  '500106000000',
  '500107000000',
  '500108000000',
  '500109000000',
  '500112000000',
  '500113000000',
  '500191000000',
  '500193000000',
])

const areaShow = computed(() => {
  let id = user.refId
  if (params2.value.regionId) {
    id = params2.value.regionId
  } else if (params2.value.streetId) {
    id = params2.value.streetId
  } else if (params2.value.communityId) {
    id = params2.value.communityId
  }
  return specialRegionId.value.includes(id)
})

const handleChangeParamsById = (id) => {
  // console.log(id)
  const node = findNodeById(cityOptions.value, id)
  // console.log(node)
  if (node) {
    if (node.parentCode === user.refId) {
      const codeArr = [node.parentCode, node.areaCode]
      handleChangeArea(codeArr)
      areaInfo.value = codeArr
    } else {
      // 这里没有考虑通用，因为这个最多直到街道，而且只有重庆和区县可以看到
      const codeArr = ['-1', node.parentCode, node.areaCode]
      handleChangeArea(codeArr)
      areaInfo.value = codeArr
    }
  }
}

const handleChangeParamsByType = (type) => {
  params.value.type = type
  infoRef.value.inputData(params.value)
}
</script>

<template>
  <div class="container">
    <div class="left-container">
      <div class="left">
        <card title="城市体检信息采集" class="info">
          <template #title-select>
            <!-- 级联筛选-->
            <el-cascader
              v-model="areaInfo"
              :options="cityOptions"
              :props="cascaderProps"
              placeholder="体检城市"
              class="area-cascader"
              :show-all-levels="false"
              @change="handleChangeArea"
              clearable
              filterable
            ></el-cascader>
          </template>
          <template #title-right>
            <!-- 按钮-->
            <!-- <el-radio-group v-model="params.type" @change="handleRadioChange">
              <el-radio-button v-if="user.roleLevel !== 3" label="street"
                >街道信息</el-radio-button
              >
              <el-radio-button label="community">社区信息</el-radio-button>
              <el-radio-button label="residence">小区信息</el-radio-button>
              <el-radio-button label="myd">居民问卷</el-radio-button>
              <el-radio-button label="zf">问题楼栋</el-radio-button>
            </el-radio-group> -->
          </template>
          <city-info
            @changeParamsById="handleChangeParamsById"
            @changeParamsByType="handleChangeParamsByType"
            ref="infoRef"
            :level="params.level"
            :type="params.type"
          />
        </card>
        <!-- <card
          title="区县体检指标填报进度"
          class="index"
          v-if="user.roleLevel !== 1 && user.roleLevel !== 3"
        >
          <template #title-select>
            <el-select
              placeholder="请选择"
              v-model="indexChecked"
              @change="handleChangeSelect"
            >
              <el-option
                v-for="item in indexOptions"
                :key="item.pkid"
                :label="item.indexName"
                :value="item.pkid"
              >
              </el-option>
            </el-select>
          </template>
          <index-info :pkid="indexChecked" ref="indexInfoRef" />
        </card> -->
      </div>
    </div>
    <!-- <div class="right">
      <card title="城市居民抽样问卷调查" class="question">
        <template #title-select>
          <el-cascader
            v-model="areaInfo2"
            :options="cityOptions"
            :props="cascaderProps"
            placeholder="体检城市"
            class="area-cascader"
            :show-all-levels="false"
            @change="handleChangeArea2"
            clearable
            filterable
          ></el-cascader>
        </template>
        <question-info
          :code-show="areaShow"
          :level="params2.level"
          ref="questionInfoRef"
        />
      </card>
    </div> -->
  </div>
</template>

<style scoped lang="scss">
.container {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  background-color: #f4f8fe;
  display: flex;
  justify-content: center;
  //flex-direction: column;
  padding: 20px;

  .left-container {
    //width: 1884px;
    overflow-x: hidden;
    overflow-y: auto;
    // margin-right: 16px;
    width: 100%;
    height: 100%;
  }

  .left {
    display: flex;
    justify-content: space-between;
    flex-direction: column;
    height: 100%;
  }

  .info {
    width: 100%;
    height: 100%;
  }
}
</style>
